<?php 
defined('RUN_KATANA') or die('Restricted access');
class User extends Object
{
	public $SessionId;
	public $Username;
	public $Email;
	public $Company;
	public $Password;
	public $Level;
	public $Group;
	public $LevelTitle;
	public $GroupTitle;
	public $Language;
	public $Groups;
	public $Activation;
	public $CreditsBought;
	public $CreditsFree;
	public $CreditsUsed;
	public $PartnerStatus;
	public $PartnerStatusDateStart;
	public $PartnerTypes;
	public $PartnerTypesArray;
	public $PartnerClicks;
	public $PartnerViews;
	public $Conversions;
	public $LogedIn;
	public $Info;
	public $Error;
	public $CookieUserId;
	public $CookiePassword;
	public $CookieLanguage;
	
	public $RegisterDate;
	public $LastvisitDate;
	public $OnlineTime;
	public $Image;
	public $ImageObject;
	public $UserContacts;
	public $UserLocations;
	
	public function getLevel() { return intval($this->Level);  }
	public function getGroup() { return intval($this->Group);  }
	public function getCreditsBought() { return intval($this->CreditsBought);  }
	public function getCreditsFree() { return intval($this->CreditsFree);  }
	public function getCreditsUsed() { return intval($this->CreditsUsed);  }
	public function getCreditsLeft() 
	{ return intval((self::getCreditsBought() + self::getCreditsFree())-self::getCreditsUsed()); }
	
	public function getPartnerStatus() { return intval($this->PartnerStatus);  }
	public function getPartnerStatusDateStart($format = '')
	{ 
		if($format != '')
		{ return self::formatDateTime($this->PartnerStatusDateStart, $format); }
		else
		{ return $this->PartnerStatusDateStart; }
	}
	public function getPartnerTypesArray()
	{
		if($this->PartnerTypes != '')
		{
			$tempArray = explode('-', $this->PartnerTypes);
			if(is_array($tempArray))
			{
				foreach(array_keys($tempArray) as $k)
				{
					if($tempArray[$k] != '')
					{ $this->PartnerTypesArray[$tempArray[$k]] = $tempArray[$k]; }
				}
				return $this->PartnerTypesArray;
			}
		}
	}
	public function getPartnerType($key = 0)
	{
		$types = self::getPartnerTypesArray();
		if(is_array($types))
		{
			if(isset($types[$key]))
			{ return $types[$key]; }
		}
	}
	public function getPartnerClicks() { return intval($this->PartnerClicks);  }
	public function getPartnerViews() { return intval($this->PartnerViews);  }
	public function getConversions() { return intval($this->Conversions);  }
	
	/* Get UserContacts */ 
	public function getUserContact($id=0)
	{ 
		if($id > 0)
		{
			self::loadUserContacts($id);
			if(is_object($this->UserContacts[$id]))
			{ return $this->UserContacts[$id]; }
		}
	}
	public function getUserContacts()
	{ 
		self::loadUserContacts();
		return $this->UserContacts; 
	}
	/* Get UserContacts End */ 
	/* Get UserLocations */ 
	public function getUserLocation($id=0)
	{ 
		if($id > 0)
		{
			self::loadUserLocations($id);
			if(is_object($this->UserLocations[$id]))
			{ return $this->UserLocations[$id]; }
		}
	}
	public function getUserLocations()
	{ 
		self::loadUserLocations();
		return $this->UserLocations; 
	}
	/* Get UserLocations End */ 
	
	public function setSessionId($val) { $this->SessionId=$val; }
	public function setLevel($val) { $this->Level=intval($val); }
	public function setGroup($val) { $this->Group=intval($val); }
	public function setCreditsBought($val) { $this->CreditsBought=intval($val); }
	public function setCreditsFree($val) { $this->CreditsFree=intval($val); }
	public function setCreditsUsed($val) { $this->CreditsUsed=intval($val); }
	public function setPartnerStatus($val) { $this->PartnerStatus=intval($val); }
	public function setPartnerClicks($val) { $this->PartnerClicks=intval($val); }
	public function setPartnerViews($val) { $this->PartnerViews=intval($val); }
	public function setConversions($val) { $this->Conversions=intval($val); }
	public function setOnlineTime($val) { $this->OnlineTime=$val;  }
	
	public function setCookieUserId($val)
	{ 
		$this->CookieUserId=intval($val);
		setcookie('KatanaUd', $val, time() + COOKIE_EXPIRE, '/', DOMAIN); // Sets the cookie id
	}
	public function setCookiePassword($val)
	{ 
		$this->CookiePassword=$val;
		setcookie('KatanaUw', $val, time() + COOKIE_EXPIRE, '/', DOMAIN); // Sets the cookie password
	}
	public function setCookieLanguage($val)
	{ 
		$this->CookieLanguage=$val;
		setcookie('KatanaLang', $val, time() + COOKIE_EXPIRE, '/', DOMAIN); // Sets the cookie language
	}
	
	public function User($id=0, $txt=false, $runSession=true) 
	{ 
		global $ac;
		self::setDataTable('users');
		
		if($id > 0)
		{ 
			self::setId($id); 
			self::loadUser();
		}
		
		if((!defined('RUN_CRON')) && ($runSession == true))
		{
			session_start();
			self::setSessionId(session_id());

			self::loadUserCookie();
			
			if(!(self::getId() > 0))
			{
				if($_SESSION['userid'] > 0)
				{ self::setId($_SESSION['userid']); }
			}
			
			if($_GET['action'] == 'logout')
			{ self::userLogout(); }
				
			if($_POST['action'])
			{
				if($_POST['action'] == 'login_user')
				{ self::loginUser(); }
				
				if($_POST['action'] == 'logout_user')
				{ self::userLogout(); }
				
				/* Incomplete function
				if($_POST['action'] == 'forgot_password')
				{ self::forgotPassword(); }
				*/
				
				if($_POST['action'] == 'reset_password')
				{ self::resetPassword(); }
			}
			
			
			
			if(!(self::getId() > 0))
			{ self::setId(0); }
			
			if(self::getId() > 0)
			{ self::loadUser(); /* echo 'load'; */ }
			else
			{ self::autoLoginUser(); /* echo 'autoload';*/ }
			
			if($ac->getSetting('SessionTrack'))
			{ self::sessionChekIn(); }
			
			if(intval($_GET['dpi']) > 0)
			{ 
				self::deleteImage();
				self::setDataChanged(true);
			}
		}
	}
	
	public function loadUserCookie()
	{
		global $katana;
		global $txt;
		if((intval($_COOKIE['KatanaUd']) > 0) && ($_COOKIE['KatanaUw'] != ''))
		{
			self::setCookieUserId($_COOKIE['KatanaUd']);
			self::setCookiePassword($_COOKIE['KatanaUw']);
		}
		if($_COOKIE['KatanaLang'] != '')
		{ self::setCookieLanguage($_COOKIE['KatanaLang']); }
		else
		{ self::setCookieLanguage($katana->getLanguage()); }
		
		if($_GET['lang'] != '')
		{
			switch($_GET['lang'])
			{
				case 'en':
				case 'ba':
				case 'no':
					 self::setCookieLanguage($_REQUEST['lang']);
				break;
			}
		}
		if(self::getCookieLanguage() != '')
		{ 
			$katana->setLanguage(self::getCookieLanguage()); 
			$txt->setLanguage(self::getCookieLanguage());
			$txt->loadWords();
		}
	}
	
	public function loadUser()
	{
		if(self::getId() > 0)
		{
			$select = 'SELECT * FROM '.DB_PERFIX.'users WHERE id='.self::getId().' LIMIT 1;'; 
			$result = mysql_query($select);
			if($result)
			{
				while($row = mysql_fetch_array($result))
				{
					self::setId($row['id']);
					self::setUsername($row['username']);
					self::setEmail($row['email']);
					self::setPassword($row['password']);
					self::setGroup($row['group']);
					self::setLevel($row['level']);
					self::setImage($row['image']);
					
					self::setCreditsBought($row['CreditsBought']);
					self::setCreditsFree($row['CreditsFree']);
					self::setCreditsUsed($row['CreditsUsed']);
					
					self::setPartnerStatus($row['PartnerStatus']);
					self::setPartnerTypes($row['PartnerTypes']);
					self::setPartnerStatusDateStart($row['PartnerStatusDateStart']);
					if(self::getImage() != '')
					{
						$this->ImageObject = new Image();
						$this->ImageObject->setFolderPath(USER_IMAGE_PATH);
						$this->ImageObject->setFolderUrl(USER_IMAGE_URL);
						$this->ImageObject->setFilename($row['image']);
					}
				}
			}
		}
	} 
	
	function saveUser()
	{
		global $txt;
		if(self::getId() > 0)
		{
			$sql  = 'UPDATE '.DB_PERFIX.'users SET ';
			$sql .= '`username`="'.$txt->formatText(self::getUsername()).'", ';
			$sql .= '`email`="'.$txt->formatText(self::getEmail()).'", ';
			$sql .= '`level`='.$txt->formatText(self::getLevel()).', ';
			$sql .= '`group`='.self::getGroup().', ';
			$sql .= '`image`="'.self::getImage().'", ';
			if(self::getPartnerStatusDateStart('Y-m-d') != '0000-00-00')
			{ $sql .= '`PartnerStatusDateStart`="'.self::getPartnerStatusDateStart('Y-m-d').'", '; }
			
			$sql .= '`CreditsBought`='.self::getCreditsBought().', ';
			$sql .= '`CreditsFree`='.self::getCreditsFree().', ';
			$sql .= '`CreditsUsed`='.self::getCreditsUsed().', ';
			
			$sql .= '`PartnerStatus`='.self::getPartnerStatus().', ';
			$sql .= '`PartnerTypes`="'.self::getPartnerTypes().'" ';
			$sql .= ' WHERE id='.self::getId().' LIMIT 1;';
			//echo $sql;
			$result = mysql_query($sql);
		}
		return;
	}
	
	function uploadImage($file)
	{
		global $thumb;
		self::deleteObjectImage(USER_IMAGE_PATH, self::getImage(), $thumb['USER_IMAGE']);
		self::setImage(self::uploadObjectImage(USER_IMAGE_PATH, $file, $thumb['USER_IMAGE'], md5(self::getId().date('Ymdhis'))));
		self::saveUser();
	}
	
	function deleteImage()
	{
		global $thumb;
		self::deleteObjectImage(USER_IMAGE_PATH, self::getImage(), $thumb['USER_IMAGE']);
		self::setImage('');
		unset($this->ImageObject);
		self::saveUser();
	}
	
	public function encryptPassword($password = '')
	{
		if($password != '')
		{
			$password = md5($password.SALT);
			return $password;
		}
	}
	
	public function changePassword($oldPassword = '', $newPassword = '')
	{
		global $katana;
		global $txt;
		if(self::getId() > 0)
		{
			if(($oldPassword == self::getPassword()) || (self::encryptPassword($oldPassword) == self::getPassword()))
			{
				$password	= '';
				if($newPassword != '')
				{ $password = self::encryptPassword($newPassword); }
				if($password != '')
				{
					$update = 'UPDATE '.DB_PERFIX.'users SET password="'.$password.'" WHERE id='.self::getId().' LIMIT 1;';
					$res = mysql_query($update);
					if(mysql_affected_rows() > 0)
					{
						$body  = ucfirst($txt->getWord('hello')).'<br /><br />';
						$body .= ucfirst($txt->getWord('you_requested_password_change')).' '.$katana->getURL().'<br /><br />';

						$body .= ucfirst($txt->getWord('your_username_is')).': '.self::getUsername().'<br />';
						$body .= ucfirst($txt->getWord('your_new_password_is')).': '.$newPassword;
						
						if($body != '')
						{
							$mail = new Email($katana);
							$mail->setTo(self::getEmail());
							$mail->setFrom($katana->getCompanyEmail());
							$mail->setFromName($katana->getCompanyName());
							$mail->setSubject(ucfirst(self::formatTextASCI($txt->getWord('you_requested_password_change'))).' '.$katana->getTitle());
							$mail->setBody($body);
							$mail->send();
							
							$katana->addAnalyticsTrack("_gaq.push(['_trackPageview', '/user/password/change/success']);");
						}
					}
				}
			}
		}
	}
	
	public function resetPassword()
	{
		if($_POST['username_email'] != '')
		{
			global $katana;
			global $txt;
			$id = self::findUserId($_POST['username_email'], $_POST['username_email']);
			if($id > 0)
			{
				$select = 'SELECT * FROM '.DB_PERFIX.'users WHERE id='.$id.' LIMIT 1;';
				$result = mysql_query($select);
				if(mysql_num_rows($result) > 0)
				{
					while ($row = mysql_fetch_object($result))
					{
						$email 		= $row->email;
						$username 	= $row->username;
						
						$possible = '0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPRSTUVZXQW';
						$code = '';
						$i = 0;
						while ($i < 7) 
						{ 
							$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
							$i++;
						}
						$password = self::encryptPassword($code);
						
						$update = 'UPDATE '.DB_PERFIX.'users SET password="'.$password.'" WHERE id='.$id.' LIMIT 1;';
						$res = mysql_query($update);
						if(mysql_affected_rows() > 0)
						{
							$body  = ucfirst($txt->getWord('hello')).'<br />';
							$body .= ucfirst($txt->getWord('you_requested_password_change')).' '.$katana->getTitle().'<br /><br />';
							$body .= ucfirst($txt->getWord('your_username_is')).': '.$username.'<br />';
							$body .= ucfirst($txt->getWord('your_new_password_is')).': '.$code;
							if($body != '')
							{						
								$mail = new Email($katana);
								$mail->setTo($email);
								$mail->setFrom($katana->getCompanyEmail());
								$mail->setFromName($katana->getCompanyName());
								$mail->setSubject(ucfirst($txt->getWord('forgot_password')).' '.$katana->getTitle());
								$mail->setBody($body);
								$mail->send();
								
								$katana->addAnalyticsTrack("_gaq.push(['_trackPageview', '/user/password/reset/success']);");
								//mail($email, ucfirst($txt->getWord('forgot_password')).' '.$katana->getTitle(), $body, $mailheader);
							}
							$this->Info['username_email'] = ucfirst($txt->getWord('your_new_password_sent_to')).':'.$email;
						}
					}
				}
			}
			else
			{ $this->Error['username_email'] = ucfirst($txt->getWord('not_found')); }
		}
	}
	
	public function forgotPassword()
	{
		if($_POST['username_email'] != '')
		{
			$id = self::findUserId($_POST['username_email'], $_POST['username_email']);
			if($id > 0)
			{
				$select = 'SELECT * FROM '.DB_PERFIX.'users WHERE id='.$id.' LIMIT 1;';
				$result = mysql_query($select);
				if($result)
				{
					global $katana;
					global $txt;
					while($row = mysql_fetch_array($result))
					{
						$activation = $row['activation'];
						$this->Info['username_email'] = 'Found:'.$row['username'];
						
						$body  = ucfirst($txt->getWord('hello')).'<br />';
						$body .= ucfirst($txt->getWord('you_requested_password_change')).' '.$katana->getTitle().'<br /><br />';
						$body .= ucfirst($txt->getWord('your_username_is')).' '.$row['username'].'<br />';
						$body .= ucfirst($txt->getWord('you_may_change_password_at')).':';
						$body .= '<a href="'.SITE_URL.'?c=16&amp;chpass='.$activation.'">'.$katana->getURL().'?c=16&amp;chpass='.$activation.'</a><br />';
						
						if($body != '')
						{
							$mailheader  = "From: post@".DOMAIN."\r\n";
							$mailheader .= "X-Mailer: PHP/".phpversion()."\r\n";
							$mailheader .= "MIME-Version: 1.0\r\n";
							if($katana->getLanguage() == 'no')
							{ $mailheader .= "Content-Type: text/html; ISO-8859-4\r\n"; }
							else
							{
								if($katana->getLanguage() == 'ba')
								{ $mailheader .= "Content-Type: text/html; ISO-8859-2\r\n"; }
								else
								{ $mailheader .= "Content-Type: text/html; ISO-8859-1\r\n"; }
							}
							$mailheader .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
							
							$katana->addAnalyticsTrack("_gaq.push(['_trackPageview', '/user/password/forgot/success']);");
							
							mail($row['email'], ucfirst($txt->getWord('forgot_password')).' '.$katana->getTitle(), $body, $mailheader);
						}
						return $body;
					}
				}
				
			}
			else
			{ $this->Error['username_email'] = 'Not found'; }
		}
	}
	
	public function loginUser($username='', $password='', $setCookie=true)
	{
		global $txt;
		if($username == '')
		{
			if($_POST['username'] != '')
			{ $username = $_POST['username']; }
			else
			{
				if($_POST['email'] != '')
				{ $username = $_POST['email']; }
			}
		}
		if($password == '')
		{ $password = $_POST['password']; }
		
		if(($username != '') && ($password != ''))
		{
			$username = trim($username);
			$password = trim($password);
			
			$remember = $_POST['remember'];
			if($txt)
			{ $this->Error['username'] = $txt->getWord('wrong_username'); }
			else
			{ $this->Error['username'] = 'No such username'; }
			$username = stripslashes($username);
			$password = stripslashes($password);
			$passwordNoEncrypt = $password;
			$password = md5($password.SALT);
			
			$sql = 'SELECT * FROM '.DB_PERFIX.'users WHERE active=1 AND (username LIKE ("'.$username.'") OR email LIKE ("'.$username.'") ';
			if((intval($username) > 0) && (intval($username) == $username))
			{ $sql .= ' OR id='.intval($username); }
			$sql .= ');';
			
			$result = mysql_query($sql);
			if(mysql_num_rows($result) > 0)
			{
				while($row = mysql_fetch_array($result))
				{
					self::setId($row['id']);
					self::setUsername($row['username']);
					self::setEmail($row['email']);
					self::setPassword($row['password']);
					self::setLevel($row['level']);
					self::setGroup($row['group']);
				}
				$this->Error['username'] = '';
				if($txt)
				{ $this->Error['password'] = $txt->getWord('wrong_password'); }
				else
				{ $this->Error['password'] = 'wrong password'; }
			}
			//echo '$password:'.$password;
			//echo '$passwordNoEncrypt:'.$passwordNoEncrypt;
			
			if((($this->Id == $username) || ($this->Username == $username) || ($this->Email == $username)) && (($this->Password == $password) || ($this->Password == $passwordNoEncrypt)))
			{
				$_SESSION['logged'] = 1;
				$_SESSION['userid'] = $this->Id;
				$_SESSION['username'] = $this->Username;
				if($remember)
				{ $_SESSION['remember'] = 'true'; }
				
				if($setCookie)
				{
					self::setCookieUserId(self::getId());
					self::setCookiePassword(self::getPassword());
				}
				
				$user_ip = $_SERVER['REMOTE_ADDR'];
				if (trim($user_ip) == '') { $user_ip = $_SERVER['HTTP_CLIENT_IP']; }
				if (trim($user_ip) == '') { $user_ip = $_SERVER['HTTP_X_FORWARDED_FOR']; }
				
				$delete = 'DELETE FROM '.DB_PERFIX.'sessions WHERE session_user_id='.$this->Id.' OR session_id = "'.session_id().'" LIMIT 1;';
				$result = mysql_query($delete);
				$insert = 	' INSERT INTO `'.DB_PERFIX.'sessions` (`session_id` , `session_user_id` , `session_start` , `session_time` , `session_ip` , `session_page` , `session_logged_in` , `session_gid` )';
				$insert .= 	' VALUES (\''.session_id().'\', \''.$this->Id.'\', NOW( ), NOW( ), \''.$user_ip.'\', \''.$_GET['m'].'\', \'1\', \'1\');';
				$result = mysql_query($insert);
				$update = 	' UPDATE `'.DB_PERFIX.'users` SET lastvisitDate = NOW() WHERE id='.$this->Id.';';
				$result = mysql_query($update);
				
				$update = 'UPDATE '.DB_PERFIX.'shop_cart_items SET user_id='.$this->Id.' WHERE session_id="'.session_id().'";';
				$result = mysql_query($update);
				
				global $katana;
				$katana->addAnalyticsTrack("_gaq.push(['_trackPageview', '/user/login/success']);");
				
				return $this->Error;
			}
			else
			{ 
				self::userUnset();
				return $this->Error; 
			}
		}
	}
	
	public function autoLoginUser()
	{
		$id = self::getCookieUserId();
		$password = self::getCookiePassword();
		
		if(($id > 0) && ($password != ''))
		{
			$select = 'SELECT * FROM '.DB_PERFIX.'users WHERE id='.$id.';';
			$result = mysql_query($select);
			if(mysql_num_rows($result) > 0)
			{
				while($row = mysql_fetch_array($result))
				{
					if($row['password'] == $password)
					{
						self::setId($row['id']);
						self::setUsername($row['username']);
						self::setEmail($row['email']);
						self::setPassword($row['password']);
						self::setLevel($row['level']);
						self::setGroup($row['group']);
						
						$_SESSION['logged'] = 1;
						$_SESSION['userid'] = self::getId();
						$_SESSION['username'] = self::getUsername();
						
						self::setCookieUserId(self::getId());
						self::setCookiePassword(self::getPassword());
					}
				}
			}
		}
	}
	
	public function userLogout()
	{
		if(self::getId() > 0)
		{
			$update = ' UPDATE `'.DB_PERFIX.'users` SET lastvisitDate = NOW() WHERE id='.$this->Id.';';
			$result = mysql_query($update);
			$selectTime = 'SELECT (session_time-session_start) AS online_time FROM '.DB_PERFIX.'sessions WHERE session_user_id='.$this->Id.' LIMIT 1;';
			$result = mysql_query($selectTime);
			while($row = mysql_fetch_array($result))
			{ $this->OnlineTime = $row['online_time']; }
			$time = mktime(0, 0, $this->OnlineTime, 0, 0, 0);
			$time = (date("H:i:s ",$time)); 
			$update = ' UPDATE `'.DB_PERFIX.'user_details` SET online_time = ADDTIME(online_time , "'.$time.'") WHERE id='.$this->Id.';';
			$result = mysql_query($update);
			$delete = 'DELETE FROM '.DB_PERFIX.'sessions WHERE session_user_id='.$this->Id.';';
			$result = mysql_query($delete);
			$delete = 'DELETE FROM '.DB_PERFIX.'shop_cart_items WHERE user_id='.$this->Id.';';
			$result = mysql_query($delete);
			
			global $katana;
			$katana->addAnalyticsTrack("_gaq.push(['_trackPageview', '/user/logout/success']);");
			
			self::userUnset();
		}
	}
	
	public function userUnset()
	{
		unset($_SESSION['logged']);
		unset($_SESSION['userid']);
		unset($_SESSION['username']);
		self::setCookieUserId(0);
		self::setCookiePassword('');
		unset($_COOKIE[session_name()]);
		unset($this->Id);
		unset($this->Username);
		unset($this->Email);
		unset($this->Password);
		unset($this->Image);
		unset($this->Level);
		unset($this->RegisterDate);
		unset($this->LastvisitDate);
		unset($this->Activation);
	}
	
	function sessionChekIn()
	{
		$sessionid = session_id();
		$session_user_id = 0;
		if($sessionid)
		{
			if(self::getId() > 0)
			{ $session_user_id = $this->Id; }
			
			$select = 'UPDATE '.DB_PERFIX.'sessions SET session_time = NOW() WHERE session_id="'.$sessId.'" AND session_user_id='.$session_user_id.' LIMIT 1;';
			$result = mysql_query($select);
			
			if(mysql_affected_rows() < 1)
			{
				$user_ip = $_SERVER['REMOTE_ADDR'];
				if (trim($user_ip) == '') { $user_ip = $_SERVER['HTTP_CLIENT_IP']; }
				if (trim($user_ip) == '') { $user_ip = $_SERVER['HTTP_X_FORWARDED_FOR']; }
				
				$insert = 	' INSERT INTO `'.DB_PERFIX.'sessions` (`session_id` , `session_user_id` , `session_start` , `session_time` , `session_ip` , `session_page` , `session_logged_in` , `session_gid` )';
				$insert .= 	' VALUES (\''.session_id().'\', \''.$session_user_id.'\', NOW( ), NOW( ), \''.$user_ip.'\', \''.$_GET['com_id'].'\', \'0\', \'0\');';
				$result = mysql_query($insert);
			}
			
			if(self::getId() > 0)
			{
				$updateUser = ' UPDATE `'.DB_PERFIX.'users` SET lastvisitDate = NOW() WHERE id='.$this->Id.';';
				$result = mysql_query($updateUser);
			}
		}
	}
	
	function findUserId($username='', $email='')
	{
		global $ac;
		$usrid = 0;
		$usrid = $ac->findUserId($username, $email);
		return $usrid;
	}
	
	function registerUser($username, $password, $email='')
	{
		if(!(self::getId() > 0))
		{
			global $ac;
			$ac->addUser($username, $password, $email='');
		}
	}
	
	function loadUserContacts($id=0)
	{
		if(!self::getItemLoaded('UserContacts'.$id))
		{
			global $db;
			if($id > 0)
			{ $sql = 'SELECT * FROM '.DB_PERFIX.'user_contacts WHERE id = '.$id.' AND userId='.self::getId().' '; }
			else
			{ $sql = 'SELECT * FROM '.DB_PERFIX.'user_contacts WHERE userId='.self::getId().' '; }
			$sql .= ' ORDER BY id ASC;';
			
			$result = $db->query($sql);
			$data = $db->fetch($sql, 0);
			
			if(is_array($data))
			{
				foreach($data as $row)
				{ $this->UserContacts[$row['id']] = new UserContact($row); }
			}
			unset($data);
			self::setItemLoaded('UserContacts'.$id, true);
		}
	}
	
	function deleteUserContact($id=0)
	{
		if($id > 0)
		{
			$sql  = 'DELETE FROM '.DB_PERFIX.'user_contacts WHERE id = '.$id.' AND userId='.self::getId().';';
			$result = mysql_query($sql);
			self::setItemLoaded('UserContacts0', 0);
			self::setItemLoaded('UserContacts'.$id, 0);
			unset($this->UserContacts);
			self::loadUserContacts(0);
		}
	}
	
	function loadUserLocations($id=0)
	{
		if(!self::getItemLoaded('UserLocations'.$id))
		{
			global $db;
			$sql  = 'SELECT ul.*, c.printable_name AS CountryName ';
			$sql .= 'FROM '.DB_PERFIX.'user_locations AS ul ';
			$sql .= 'LEFT JOIN '.DB_PERFIX.'country AS c ON (ul.country=c.iso) ';
			if($id > 0)
			{ $sql .= ' WHERE ul.id = '.$id.' AND ul.userId='.self::getId().' '; }
			else
			{ $sql .= ' WHERE ul.userId='.self::getId().' '; }
			$sql .= ' ORDER BY id ASC;';
			
			$result = $db->query($sql);
			$data = $db->fetch($sql, 0);
			
			if(is_array($data))
			{
				foreach($data as $row)
				{ $this->UserLocations[$row['id']] = new UserLocation($row); }
			}
			unset($data);
			self::setItemLoaded('UserLocations'.$id, 1);
		}
	}
	
	function deleteUserLocation($id=0)
	{
		if($id > 0)
		{
			$sql  = 'DELETE FROM '.DB_PERFIX.'user_locations WHERE id = '.$id.' AND userId='.self::getId().';';
			$result = mysql_query($sql);
			self::setItemLoaded('UserLocations0', 0);
			self::setItemLoaded('UserLocations'.$id, 0);
			unset($this->UserLocations);
			self::loadUserLocations(0);
		}
	}
	
	function upgradePartnerStatus($newStatus=0)
	{
		$returnValue = 0;
		if($newStatus > 0)
		{
			if(self::getPartnerStatus() < $newStatus)
			{
				self::setPartnerStatus($newStatus);
				self::setPartnerStatusDateStart(date('Y-m-d'));
				self::saveUser();
				self::sendPartnerStatusUpgradeMail($newStatus);
				$returnValue = $newStatus;
			}
			else
			{
				self::setPartnerStatus($newStatus);
				self::setPartnerStatusDateStart(date('Y-m-d'));
				self::saveUser();
				$returnValue = $newStatus;
			}
		}
		else
		{
			switch(self::getPartnerStatus())
			{
				case 1:
					self::setPartnerStatus(1);
					self::saveUser();
					self::sendPartnerStatusRequestMail();
					$returnValue = 1;
				break;
				case 5:
					self::setPartnerStatus(15);
					self::setPartnerStatusDateStart(date('Y-m-d'));
					self::saveUser();
					self::sendPartnerStatusUpgradeMail(15);
					$returnValue = 15;
				break;
				case 15:
					self::setPartnerStatus(10000);
					self::setPartnerStatusDateStart(date('Y-m-d'));
					self::saveUser();
					self::sendPartnerStatusUpgradeMail('unlimited');
					$returnValue = 10000;
				break;
			}
		}
		return $returnValue;
	}
	
	function sendPartnerStatusRequestMail()
	{
		global $katana;
		global $txt;
		global $mailCSS;

		$body = '<body style="'.$mailCSS['fontstyle'].'">';
		$body .= '<h3 style="'.$mailCSS['fontstyleHeading'].'">'.ucfirst($txt->getWord('partner_account').' '.$txt->getWord('request').' '.$txt->getWord('recived')).'</h3>';
		$body .= '<p style="'.$mailCSS['fontstyle'].'"><br />Takk for foresp&oslash;rsel etter AnLast partnerkonto.<br />Vi vil behandle din foresp&oslash;rsel s&aring; snart som mulig.</p>';
		$body .= $katana->getCompanyMailFooter($fontstyle);
		$body .= '<a href="'.SITE_URL.'"><img width="232" height="40" border="0" alt="'.$katana->getTitle().' Logo" src="'.SITE_URL.'files/images/LogoAnLast.png" /></a>';
		$body .= '</body>';
		
		$mail = new Email();
		$mail->setTo(self::getEmail());
		$mail->setCC($katana->getCompanyEmail());
		$mail->setFrom($katana->getCompanyEmail());
		$mail->setFromName($katana->getTitle());
		$mail->setReplyTo($katana->getCompanyEmail());
		$mail->setSubject(ucfirst($txt->getWord('partner_account').' '.$txt->getWord('order_confirmation')));
		$mail->setBody($body);
		$mail->send();
	
		$body = '<body style="'.$mailCSS['fontstyle'].'">';
		$body .= '<h3 style="'.$mailCSS['fontstyleHeading'].'">'.ucfirst($txt->getWord('partner_account').' '.$txt->getWord('request').' '.$txt->getWord('recived')).'</h3>';
		$body .= '<p style="'.$mailCSS['fontstyle'].'"><br />';
		$body .= 'En bruker har bestilt partnerkonto.<br />';
		$body .= 'F&oslash;lgende informasjon er registrert p&aring; brukeren:<br /><br />';
		$body .= ucfirst($txt->getWord('username')).': '.self::getUsername().'<br />';
		$body .= ucfirst($txt->getWord('e-mail')).': '.self::getEmail().'<br /><br />';
		$body .= '<a href="'.SITE_URL.'commander/?con=2&user='.self::getId().'">Klikk her for brukeradministrering.</a><br />';
		$body .= '</p>';
		$body .= $katana->getCompanyMailFooter($fontstyle);
		$body .= '<a href="'.SITE_URL.'"><img width="232" height="40" border="0" alt="'.$katana->getTitle().' Logo" src="'.SITE_URL.'files/images/LogoAnLast.png" /></a>';
		$body .= '</body>';
		
		$mail = new Email();
		$mail->setTo($katana->getCompanyEmail());
		$mail->setFrom($katana->getCompanyEmail());
		$mail->setFromName($katana->getTitle());
		$mail->setReplyTo($katana->getCompanyEmail());
		$mail->setSubject('Partnerkonto bestilling');
		$mail->setBody($body);
		$mail->send();
		
		$katana->addAnalyticsTrack("_gaq.push(['_trackPageview', '/user/partner/request/success']);");
	}
	
	function sendPartnerStatusUpgradeMail($limit = '')
	{
		global $katana;
		global $txt;
		global $mailCSS;
		
		$content = ucfirst($txt->getWord('your_partner_account_can_have_count_active_ads'));
		
		if(is_numeric($limit) && (intval($limit) < 10000))
		{ $count = $limit; }
		else
		{ $count = $txt->getWord('unlimited'); }
		
		$body .= '<body style="'.$mailCSS['fontstyle'].'">';
		$body .= '<h3 style="'.$mailCSS['fontstyleHeading'].'">'.ucfirst($txt->getWord('your_partner_account_upgraded')).'</h3>';
		$body .= '<p style="'.$mailCSS['fontstyle'].'"><br />'.str_replace('$count', $count, $content).'</p>';
		$body .= $katana->getCompanyMailFooter($fontstyle);
		$body .= '<a href="'.SITE_URL.'"><img width="232" height="40" border="0" alt="'.$katana->getTitle().' Logo" src="'.SITE_URL.'files/images/LogoAnLast.png" /></a>';
		$body .= '</body>';
		
		$mail = new Email();
		$mail->setTo(self::getEmail());
		$mail->setCC($katana->getCompanyEmail());
		$mail->setFrom($katana->getCompanyEmail());
		$mail->setFromName($katana->getTitle());
		$mail->setReplyTo($katana->getCompanyEmail());
		$mail->setSubject(ucfirst($txt->getWord('your_partner_account_upgraded')));
		$mail->setBody($body);
		$mail->send();
		
		$katana->addAnalyticsTrack("_gaq.push(['_trackPageview', '/user/partner/upgrade/success']);");
	}
}
?>